package com.wwdx.wechat.handler;

import com.wwdx.model.WwdxBookModel;
import com.wwdx.model.WwdxVipUserModel;
import com.wwdx.model.WwdxWeixinUserModel;
import com.wwdx.utils.ConstantHolder;
import com.wwdx.wechat.WxConstant;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.common.util.http.URIUtil;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * @author liguoliang
 */
public abstract class AbstractMsgHandler extends AbstractHandler {

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) {
        String openId = wxMessage.getFromUser(),content = wxMessage.getContent(),replay = "回复书籍名、作者名关键字查询";
        boolean td = "TD".equalsIgnoreCase(content),dy = "DY".equalsIgnoreCase(content);
        if (td || dy){
            WwdxWeixinUserModel wwdxWeixinUserModel = wwdxWeixinUserService.getByOpenId(openId);
            String unionid = wwdxWeixinUserModel.getUnionid();
            WwdxVipUserModel wwdxVipUserModel = wwdxVipUserService.getByUnionId(unionid);
            if (td){
                if (wwdxVipUserModel != null){
                    wwdxVipUserModel.setSubscribe(0);
                    wwdxVipUserService.update(wwdxVipUserModel);
                }
                setOperations.remove(ConstantHolder.USER_SUBSCRIBE_TOTAL_SET,unionid);
                replay = "退订成功";
            }
            if (dy){
                if (wwdxVipUserModel != null){
                    wwdxVipUserModel.setSubscribe(1);
                    wwdxVipUserService.update(wwdxVipUserModel);
                }
                replay = "订阅成功";
            }
            return WxMpXmlOutMessage.TEXT().content(replay).fromUser(wxMessage.getToUser()).toUser(openId).build();
        }

        //书籍或书籍作者名关键字查询
        WwdxBookModel model = WwdxBookModel.builder().type(0).status(0).word(content).build();
        List<WwdxBookModel> wwdxBookModels = wwdxBookService.selectModelList(model,1,1);
        if (!CollectionUtils.isEmpty(wwdxBookModels)){
            WwdxBookModel wwdxBookModel = wwdxBookModels.get(0);
            String bookname = wwdxBookModel.getBookname();
            Long bookid = wwdxBookModel.getBookid(),copywriter = wwdxBookModel.getCopywriter(),videoauthorid = wwdxBookModel.getVideoauthorid();
            String url = URIUtil.encodeURIComponent(wechatUrl+String.format(WxConstant.SINGLEBOOK_PAGE,bookid,videoauthorid,copywriter));
            String s = wechatUrl+"auth.html?url="+url;
            replay = String.format(WxConstant.SEARCH_BOOK_OR_THEME_REPLAY,s,bookname);
        }
        return WxMpXmlOutMessage.TEXT().content(replay).fromUser(wxMessage.getToUser()).toUser(openId).build();
    }
}